package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author wangqian
 */
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还没有库存新增操作
        List<WareSkuEntity> list = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id",skuId).eq("ware_id",wareId));
        if(list==null||list.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //todo 设置sku的名称  如果失败，整个事物不需要回滚
            //1、自己catch异常
            //TOdo 异常出现后不回滚
            try{
                R rInfo = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String,Object>)rInfo.get("skuInfo");
                if(rInfo.getCode()==0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            wareSkuDao.insert(wareSkuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> vos = skuIds.stream().map(id->{
            SkuHasStockVo vo = new SkuHasStockVo();
            vo.setSkuId(id);
            Long count = baseMapper.getSkuStock(id);
            if(count>0){
                vo.setHasStock(true);
            }else {
                vo.setHasStock(false);
            }
            //查询当前sku的总库存量
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    /**
     * 为某个订单锁定库存
     *
     * 默认只要是运行时异常，都会进行回滚
     * @param wareSkuLockVo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        //1、按照下单的收货地址，找到就近仓库，锁定库存

        //1、找到每个商品在哪个仓库都有库存

        List<OrderItemVo> locks = wareSkuLockVo.getLocks();

        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(item->{
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            List<Long> wareIds = wareSkuDao.ListWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for(SkuWareHasStock stock:skuWareHasStocks){
            boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if(wareIds==null||wareIds.size()==0){
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            for(Long wareId: wareIds){
                //成功返回1，否则返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,stock.getNum());
                if(count==0){
                    //当前商品当前仓库锁定失败，重试下一个仓库
                }else if(count==1){
                    skuStocked = true;
                    break;
                }
            }
            if(skuStocked==false){
                //当前商品所有库存都没有锁住
                throw new NoStockException(skuId);
            }
        }
        //3、肯定全部都是锁定成功状态
        return true;
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }
}